package com.zhongxi.guoyuan.view.user;

import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.code.CodeResult;
import com.zhongxi.guoyuan.entity.user.RegisterCheckResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.RegularTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ForgotPasswordActivity extends BaseActivity implements View.OnClickListener {

    private Button btSend;
    private EditText etPhone;
    private EditText etCode;
    private Button btSure;
    private EditText etPassword;
    private String code;
    private String phone;
    private String type;
    private Map<String, String> map = new HashMap<String, String>();
    private int flag;
    private int position;

    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            btSend.setClickable(false);
            btSend.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            btSend.setText("发送验证码");
            btSend.setClickable(true);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_forgot);
        initTitle();
        flag = getIntent().getIntExtra("type",0);
        if(flag == 0){
            tvTitle.setText("重置密码");
        }else if(flag == 1){
            tvTitle.setText("设置密码");
        }
        etPhone = (EditText) findViewById(R.id.etPhone);
        btSend = (Button) findViewById(R.id.btSend);
        etCode = (EditText) findViewById(R.id.etCode);
        btSure = (Button) findViewById(R.id.btSure);
        etPassword = (EditText) findViewById(R.id.etPassword);
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        btSend.setOnClickListener(this);
        btSure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.btSend:
                sendCode();
                break;
            case R.id.btSure:
                check();
                break;
        }
    }

    /**
     * 注册前校验
     */
    private void check() {
        getValue();
        type = "registerCheck";
        map.clear();
        map.put("mobilenum", phone);
        SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
        sharedPrefrences.edit().putString("phone", phone).commit();
        map.put("veriycode", code);
        map.put("msgid", MyApplication.getInstance().getMsgid());
        getServer(Url.REGISTER_CHECK, map, "", false, null, "post");
    }

    /**
     * 重置密码
     */
    private void setPassword() {
        Map<String, String> map = new HashMap<String, String>();
        map.clear();
        type = "setPassword";
        map.put("useid", MyApplication.getInstance().getUseId());
        map.put("newpwd", MyApplication.getInstance().descsc(etPassword.getText().toString().trim()));
        map.put("oldpwd","");
        getServer(Url.SET_PWD, map,"", false, null, "post");
    }

    /**
     * 发送验证码
     */
    private void sendCode() {
        getValue();
        if(TextUtils.isEmpty(phone)){
            showShortToast("手机号不能为空");
        }else if(!RegularTool.isPhoneNumberValid(phone)){
            showShortToast("请输入正确的手机号");
        }else{
            type = "sendcode";
            TimeCount time = new TimeCount(60000, 1000);
            time.start();
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPrefrences.edit().putString("phone", phone).commit();
            map.clear();
            map.put("mobilenum", phone);
            getServer(Url.SEND_CODE, map, "", false, null, "post");
        }
    }

    private void getValue() {
        phone = etPhone.getText().toString().trim();
        code = etCode.getText().toString().trim();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        try {
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            Gson gson = new Gson();
            if ("sendcode".equals(type)) {
                CodeResult result = gson.fromJson(response, CodeResult.class);
//                Toast.makeText(this, "成功", Toast.LENGTH_LONG).show();
                sharedPrefrences.edit().putString("now", result.getSafeobj().getNow()).commit();
                sharedPrefrences.edit().putString("sk", result.getSafeobj().getSafestring()).commit();
                sharedPrefrences.edit().putString("msgid", result.getMsgid()).commit();
            }else if("registerCheck".equals(type)){
                RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
                sharedPrefrences.edit().putString("useid", result.getId()).commit();
                sharedPrefrences.edit().putString("now", result.getSafeobj().getNow()).commit();
                sharedPrefrences.edit().putString("sk", result.getSafeobj().getSafestring()).commit();
                setPassword();
            }else if ("setPassword".equals(type)) {
                startAct(LoginActivity.class);
                finish();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        try {
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            Gson gson = new Gson();
            BaseResponse result1 = gson.fromJson(response, BaseResponse.class);
            if (null != result1.getSafeobj() && !"".equals(result1.getSafeobj()))
                MyApplication.getInstance().setSpValue(result1.getSafeobj());
            JSONObject obj = new JSONObject(response);
            int errorcode = obj.getInt("code");
            if (errorcode == 1000) {
//                showShortToast("参数错误");
            } else if (errorcode == 1010) {
//                showShortToast("重复请求");
            } else if (errorcode == 1011) {
                showShortToast("短信已失效");
            } else if (errorcode == 1003) {
                showShortToast("用户已登录");
            } else if (errorcode == 1012) {
                showShortToast("验证码错误");
            } else if (errorcode == 7001) {
                //                showShortToast("您是老用户，已设置密码");
                RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
                sharedPrefrences.edit().putString("useid", result.getId()).commit();
                sharedPrefrences.edit().putString("now", result.getSafeobj().getNow()).commit();
                sharedPrefrences.edit().putString("sk", result.getSafeobj().getSafestring()).commit();
//                showShortToast("检查成功");
                setPassword();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void processOldUser(String response) {
        super.processOldUser(response);
        SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
        Gson gson = new Gson();
        RegisterCheckResult result = gson.fromJson(response, RegisterCheckResult.class);
        if(null!=result&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        sharedPrefrences.edit().putString("useid", result.getId()).commit();
        sharedPrefrences.edit().putString("now", result.getSafeobj().getNow()).commit();
        sharedPrefrences.edit().putString("sk", result.getSafeobj().getSafestring()).commit();
//        startAct(SetPasswordActivity.class);
        setPassword();
    }
}
